package com.fmjr.common.util;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @author lun.li@163.com
 * @Description: 字符串工具类
 * @date 2017年4月6日 上午10:08:53 
 * @version V1.0
 */
public class StringUtils extends org.apache.commons.lang.StringUtils {

	private static final String ENCODING_DEFAULT = "UTF-8";
	private static final boolean NOCACHE_DEFAULT = true;

	/**
	 * 根据输入的时间格式判断是否是日期类型的字符串
	 * 
	 * @param str
	 *            要判断的字符
	 * @param format
	 *            判断是否匹配对应的格
	 * @return 返回匹配结果
	 */
	public static boolean isDate(String str, String format) {
		if (StringUtils.isEmpty(str))
			return false;
		if (StringUtils.isEmpty(format))
			return false;
		try {
			DateFormat df = new SimpleDateFormat(format);
			df.parse(str);
		} catch (Exception ex) {
			return false;
		}

		return true;
	}

	/**
	 * 将字符串str按reg的规则分解
	 * 
	 * @param str
	 * @param reg
	 *            如 '|'与':'等
	 * @return
	 */
	public static ArrayList<String> stringToArrayList(String str, String reg) {

		ArrayList<String> tmp = new ArrayList<String>();
		if (str == null)
			return tmp;
		String[] strArr = StringUtils.split(str, reg);
		if (str.length() > 0) {
			for (int i = 0; i < strArr.length; ++i) {
				tmp.add(strArr[i]);
			}
		}
		return tmp;
	}

	public static String toUnicode(String strText, String code) throws UnsupportedEncodingException {
		char c;
		String strRet = "";
		int intAsc;
		String strHex;
		// strText = new String(strText.getBytes("iso8859_1"), code);
		for (int i = 0; i < strText.length(); i++) {
			c = strText.charAt(i);
			intAsc = (int) c;
			if (intAsc > 128) {
				strHex = Integer.toHexString(intAsc);
				strRet = strRet + "&#x" + strHex + ";";
			} else {
				strRet = strRet + c;
			}
		}
		return strRet;
	}

	/**
	 * 数字格式化
	 * 
	 * @param d
	 */
	public static String numFormat(Double d) {
		NumberFormat nf = NumberFormat.getNumberInstance();
		nf.setMaximumFractionDigits(2);
		return nf.format(d);
	}

	public static boolean checkNull(String str) {
		if (str == null || "".equals(str)) {
			return true;
		}
		return false;
	}

	private static void render(final HttpServletResponse response, final String contentType, final String content) {
		try {
			String encoding = ENCODING_DEFAULT;
			boolean noCache = NOCACHE_DEFAULT;

			String fullContentType = contentType + ";charset=" + encoding;
			response.setContentType(fullContentType);
			if (noCache) {
				response.setHeader("Pragma", "No-cache");
				response.setHeader("Cache-Control", "no-cache");
				response.setDateHeader("Expires", 0);
			}

			response.getWriter().write(content);
			response.getWriter().flush();

		} catch (IOException e) {
			throw new RuntimeException("");
		}
	}

	public static void renderText(final HttpServletResponse response, final String text) {
		render(response, "text/plain", text);
	}

	public static void renderXml(final HttpServletResponse response, final String text) {
		render(response, "text/xml", text);
	}

	public static void renderJson(final HttpServletResponse response, final String text) {
		render(response, "text/plain", text);
	}

	/**
	 * 生成随机字符串
	 * 
	 * @param length
	 * @return String
	 */
	public static String randomStr(int length) {
		// 数字 大小写字母
		StringBuffer buffer = new StringBuffer("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
		StringBuffer str = new StringBuffer();
		Random r = new Random();
		int range = buffer.length();
		for (int i = 0; i < length; i++) {
			str.append(buffer.charAt(r.nextInt(range)));
		}
		return str.toString();
	}

	/**
	 * 生成随机字符串
	 * 
	 * @param length
	 * @return String
	 */
	public static String randomNum(int length) {
		// 数字 大小写字母
		StringBuffer buffer = new StringBuffer("0123456789");
		StringBuffer str = new StringBuffer();
		Random r = new Random();
		int range = buffer.length();
		for (int i = 0; i < length; i++) {
			str.append(buffer.charAt(r.nextInt(range)));
		}
		return str.toString();
	}

	/**
	 * 截取字符串
	 * 
	 * @param src
	 * @param len
	 * @return
	 */
	public static String getSubWord(String src, int len) {
		StringBuilder sb = new StringBuilder();
		char[] c = src.toCharArray();
		for (int x = 0; x < c.length; x++) {
			sb.append(c[x]);
			if (sb.toString().getBytes().length > len) {
				return sb.substring(0, x);
			}
		}
		return src;
	}

	/**
	 * 转义xml特殊字符
	 * 
	 * @param str
	 * @return
	 */
	public static String XmlEscape(String str) {

		if (str.indexOf("&") == -1 && str.indexOf("\"") == -1 && str.indexOf("\'") == -1 && str.indexOf("<") == -1 && str.indexOf(">") == -1) {
			return str;
		} else {
			str = str.replaceAll("&", "&amp;");
			str = str.replaceAll("\"", "&quot;");
			str = str.replaceAll("'", "&apos;");
			str = str.replaceAll("<", "&lt;");
			str = str.replaceAll(">", "&gt;");
			return str;
		}
	}

	/**
	 * 数字补零
	 * 
	 * @param length
	 *            输出 长度
	 * @param number
	 *            输入 数字
	 * @return 0000000*
	 */
	public static String lpad(int length, Long number) {
		String f = "%0" + length + "d";
		return String.format(f, number);
	}

	/**
	 * @param htmlStr
	 * @return 删除Html标签
	 */
	public static String delHTMLTag(String htmlStr) {
		String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式
		String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式
		String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
		String regEx_space = "\\s*|\t|\r|\n";// 定义空格回车换行符
		Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
		Matcher m_script = p_script.matcher(htmlStr);
		htmlStr = m_script.replaceAll(""); // 过滤script标签

		Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
		Matcher m_style = p_style.matcher(htmlStr);
		htmlStr = m_style.replaceAll(""); // 过滤style标签

		Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
		Matcher m_html = p_html.matcher(htmlStr);
		htmlStr = m_html.replaceAll(""); // 过滤html标签

		Pattern p_space = Pattern.compile(regEx_space, Pattern.CASE_INSENSITIVE);
		Matcher m_space = p_space.matcher(htmlStr);
		htmlStr = m_space.replaceAll("").replaceAll("&nbsp;",""); // 过滤空格回车标签
		return htmlStr.trim(); // 返回文本字符串
	}
	
	/***
	 *格式化手机号
	 *例如：
	 *in  :158 0000 5678
	 *res :158 **** 5678
	 * @param mobile
	 * @return
	 */
	public static String formatMobile(String mobile) {
		if(mobile == null) return  "";
		String start = mobile.substring(0, 3);
		String end = mobile.substring(8, 11);
		return start+"****"+end;
	}
	/***
	 * 格式 字符串
	 * @param str  需要格式的字符串  
	 * @param length 字符串的总长度
	 * @param start  0-start 保留     if=0 前面的全部格式化
	 * @param end  end -长度  保留      if=0 后面的全部格式化
	 * @return
	 */
	public static String formatString(String str,int length,int start,int end) {
		if(str == null) return  "";
		String strStart ="";
		String strEnd = "";
		if(start == 0){ //前面的全部格式化
			if(end != 0){
				strEnd =  str.substring(length - end, length);
			}
		}else{
			strStart = str.substring(0, start);
		}
		if(end == 0){ //后面的全部格式化
			if(start != 0){
				strStart = str.substring(0, start);
			}
		}else{
			strEnd =  str.substring(length - end, length);
		}
		String a = "";
		if(length - start - end >0){
			for(int i=0;i<(length - start - end);i++){
				a += "*";
			}
		}
		
		return strStart+a+strEnd;
	}
	 public static void main(String[] args) {
		String str = "13408678419";
		String resstr = StringUtils.formatString(str, str.length(), 3, 3);
		System.out.println(resstr);
	}
}
